package edu.gd.servlet;

import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import edu.gd.dao.UserDao;
import edu.gd.entity.BaseResponse;
import edu.gd.entity.User;
import edu.gd.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/update/plus")
public class UserUpdatePlusServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String jsonStu= RequestUtil.getRequestBody(req);
        Gson gson=new Gson();
        User u1Body=gson.fromJson(jsonStu,User.class);
        User u1= UserDao.getUserByID(u1Body.getUsername());
        int rows=0;
        if(u1!=null&&!StringUtils.isEmptyOrWhitespaceOnly(u1Body.getSex())){
            u1.setSex(u1Body.getSex());
            u1.setQuestion(u1Body.getQuestion());
            u1.setAnswer(u1Body.getAnswer());
            u1.setIntroduce(u1Body.getIntroduce());
        }
        rows=UserDao.updateUserByUser(u1);
        resp.setContentType("application/json;character=utf-8");
        BaseResponse baseResponse=new BaseResponse();
        if(rows>0){
            baseResponse.setCode(200);
            baseResponse.setMsg("修改成功");
        }
        else{
            baseResponse.setCode(500);
            baseResponse.setMsg("修改失败");
        }
        PrintWriter out =resp.getWriter();
        out.write(gson.toJson(baseResponse));
        out.flush();
    }
}
